package com.eduplatform.controller;

import com.eduplatform.common.Result;
import com.eduplatform.dto.LoginDTO;
import com.eduplatform.dto.RegisterDTO;
import com.eduplatform.entity.User;
import com.eduplatform.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody @Valid LoginDTO loginDTO) {
        String token = userService.login(loginDTO.getUsername(), loginDTO.getPassword());

        if (token != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            return Result.success(map);
        } else {
            return Result.error("Invalid username or password");
        }
    }

    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody @Valid RegisterDTO registerDTO) {
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);

        boolean result = userService.register(user);

        if (result) {
            return Result.success(true);
        } else {
            return Result.error("Username already exists");
        }
    }

    @PostMapping("/logout")
    public Result<Boolean> logout(@RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 检查token是否为空
            if (token == null || token.isEmpty()) {
                logger.warn("登出请求未提供token");
                // 对前端来说，没有token也算是已登出状态
                return Result.success(true);
            }

            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }

            // 检查token格式，如果格式不正确，也视为已登出
            if (!token.contains(".") || token.split("\\.").length != 3) {
                logger.warn("登出请求提供了无效的token格式");
                return Result.success(true);
            }

            // 尝试使token失效
            userService.logout(token);

            // 无论后端处理是否成功，对前端用户来说都已经登出
            return Result.success(true);
        } catch (Exception e) {
            logger.error("登出处理异常", e);
            // 即使出现异常，也返回成功，因为对用户来说已经登出
            return Result.success(true);
        }
    }
}